import { useEffect, useMemo, useRef, useState } from 'react'
import { useEnhancedSSEChat } from '../hooks/useEnhancedSSEChat'
import { useSpeechInput } from '../hooks/useSpeechInput'
import { Mic, Send, ArrowLeft, CheckCircle, Eye, Edit, Trash2, Copy, Clock, MoreVertical } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import rehypeHighlight from 'rehype-highlight'
import 'highlight.js/styles/github.css'
import ChartMessage from '../components/chat/ChartMessage'

export default function ChatPage() {
  const navigate = useNavigate()
  const { messages, isStreaming, error, send, cancel, taskActions } = useEnhancedSSEChat([
    { role: 'system', content: '你好，我是AIDE助手，可以帮你创建/调整任务、安排时间与提醒。' }
  ])
  const { supported, recording, transcribing, start, stopAndTranscribe } = useSpeechInput()
  const [input, setInput] = useState('')
  const [editingMessageId, setEditingMessageId] = useState<string | null>(null)
  const [editingContent, setEditingContent] = useState('')
  const [showQuickReplies, setShowQuickReplies] = useState(false)
  const listRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    // 新消息时滚动到底部
    listRef.current?.scrollTo({ top: listRef.current.scrollHeight, behavior: 'smooth' })
  }, [messages, isStreaming])

  const placeholder = useMemo(() => recording ? '正在录音...' : transcribing ? '正在转写...' : '输入消息...', [recording, transcribing])

  // 快捷回复模板 - 涵盖所有AI工具功能
  const quickReplies = [
    // 任务管理
    "查询我的任务列表",
    "创建一个新任务",
    "显示今天要完成的任务",
    "查看高优先级任务",
    "帮我安排明天的日程",
    "完成任务统计",
    
    // 看板管理
    "显示看板视图",
    "移动任务到进行中",
    "更新任务状态",
    
    // 统计分析
    "生成任务完成率图表",
    "显示效率指标",
    "分析任务趋势",
    "生成优先级分布图",
    
    // 通知设置
    "查看通知设置",
    "设置任务提醒",
    "更新通知偏好",
    
    // 图表生成
    "生成任务统计图表",
    "创建效率分析图",
    "显示时间趋势图"
  ]

  const handleSend = async () => {
    if (!input.trim() || isStreaming) return
    await send(input.trim())
    setInput('')
    setShowQuickReplies(false)
  }

  const handleVoice = async () => {
    if (recording) {
      const text = await stopAndTranscribe()
      if (text) {
        setInput(text)
      }
      return
    }
    await start()
  }

  const handleCopyMessage = (content: string) => {
    navigator.clipboard.writeText(content)
    // 可以添加一个toast提示
  }

  const handleEditMessage = (messageId: string, content: string) => {
    setEditingMessageId(messageId)
    setEditingContent(content)
  }

  const handleSaveEdit = async () => {
    if (!editingContent.trim()) return
    await send(editingContent.trim())
    setEditingMessageId(null)
    setEditingContent('')
  }

  const handleCancelEdit = () => {
    setEditingMessageId(null)
    setEditingContent('')
  }

  const handleQuickReply = (reply: string) => {
    setInput(reply)
    setShowQuickReplies(false)
  }

  const formatTime = (timestamp?: string) => {
    if (!timestamp) return ''
    try {
      // 处理时间戳，可能是数字字符串或日期字符串
      const date = new Date(timestamp)
      if (isNaN(date.getTime())) {
        return ''
      }
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    } catch (error) {
      return ''
    }
  }

  return (
    <div className="h-[calc(100vh-80px)] flex flex-col bg-slate-50">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-slate-200 bg-white flex-shrink-0">
        <div className="flex items-center gap-3">
          <button
            onClick={() => navigate(-1)}
            className="p-2 rounded-lg hover:bg-slate-100 transition-colors"
            title="返回"
          >
            <ArrowLeft size={20} />
          </button>
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-lg flex items-center justify-center">
              <span className="text-white font-bold text-sm">AI</span>
            </div>
            <div>
              <div className="font-semibold text-slate-900">AI 助手</div>
              <div className="text-xs text-slate-500">智能任务管理助手</div>
            </div>
          </div>
        </div>
        <div className="text-xs text-slate-500">
          {isStreaming ? '正在思考...' : '在线'}
        </div>
      </div>

      {/* Messages */}
      <div ref={listRef} className="flex-1 p-4 space-y-4 overflow-y-auto">
        {messages.filter(m => m.role !== 'system').map((m, i) => (
          <div key={i} className={`flex ${m.role === 'user' ? 'justify-end' : 'justify-start'} group`}>
            <div className={`max-w-[80%] ${m.role === 'user' ? 'order-2' : 'order-1'}`}>
              {m.role === 'assistant' && (
                <div className="flex items-center gap-2 mb-1">
                  <div className="w-6 h-6 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-full flex items-center justify-center">
                    <span className="text-white text-xs font-bold">AI</span>
                  </div>
                  <span className="text-xs text-slate-500">AI 助手</span>
                  <span className="text-xs text-slate-400 flex items-center gap-1">
                    <Clock size={12} />
                    {formatTime(m.messageId) || '刚刚'}
                  </span>
                </div>
              )}
              {m.role === 'user' && (
                <div className="flex items-center gap-2 mb-1 justify-end">
                  <span className="text-xs text-slate-400 flex items-center gap-1">
                    {formatTime(m.messageId) || '刚刚'}
                    <Clock size={12} />
                  </span>
                  <span className="text-xs text-slate-500">你</span>
                </div>
              )}
              <div className={`inline-block rounded-2xl px-4 py-3 text-sm leading-relaxed relative group ${
                m.role === 'user' 
                  ? 'bg-blue-600 text-white' 
                  : 'bg-white text-slate-900 border border-slate-200 shadow-sm'
              }`}>
                {m.role === 'assistant' ? (
                  <div className="prose prose-sm max-w-none">
                    {/* 函数调用状态显示 - 独立的状态条 */}
                    {(m.functionCall || m.functionResult || m.functionError) && (
                      <div className="mb-3 p-2 rounded-lg border-l-4 bg-slate-50">
                        <div className="flex items-center gap-2 text-xs">
                          {m.functionCall && (
                            <>
                              <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
                              <span className="text-blue-600 font-medium">
                                🔧 正在执行: {m.functionCall.chineseName || m.functionCall.name}
                              </span>
                            </>
                          )}
                          {m.functionResult && !m.functionCall && (
                            <>
                              <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                              <span className="text-green-600 font-medium">
                                ✅ {m.functionResult.chineseName || '函数'}执行完成
                              </span>
                            </>
                          )}
                          {m.functionError && !m.functionCall && (
                            <>
                              <div className="w-2 h-2 bg-red-500 rounded-full"></div>
                              <span className="text-red-600 font-medium">
                                ❌ {m.functionError.chineseName || '函数'}执行失败
                              </span>
                            </>
                          )}
                        </div>
                        
                        {/* 可折叠的函数调用详细信息 */}
                        <details className="mt-2">
                          <summary className="text-xs text-slate-500 cursor-pointer hover:text-slate-700 font-medium">
                            查看详细信息
                          </summary>
                          
                          {/* 函数调用信息 */}
                          {m.functionCall && (
                            <div className="mt-1 p-2 bg-slate-50 border border-slate-200 rounded-lg">
                              <div className="text-xs text-slate-600">
                                <div className="font-medium flex items-center gap-2">
                                  <span className="text-indigo-600">🔧</span>
                                  <span>正在执行: {m.functionCall.chineseName || m.functionCall.name}</span>
                                  {m.functionCall.chineseName && (
                                    <span className="text-slate-400 text-xs">({m.functionCall.name})</span>
                                  )}
                                </div>
                                <div className="mt-1 font-mono text-xs overflow-x-auto">
                                  <pre className="whitespace-pre-wrap break-all bg-slate-100 p-1 rounded">
                                    {JSON.stringify(m.functionCall.arguments, null, 2)}
                                  </pre>
                                </div>
                              </div>
                            </div>
                          )}
                          
                          {/* 函数结果显示 */}
                          {m.functionResult && (
                            <div className="mt-1 p-2 bg-green-50 border border-green-200 rounded-lg">
                              <div className="text-xs text-green-600 font-medium">
                                {m.functionResult.message}
                              </div>
                              <div className="mt-1 font-mono text-xs overflow-x-auto">
                                <pre className="whitespace-pre-wrap break-all bg-green-100 p-1 rounded">
                                  {JSON.stringify(m.functionResult.result, null, 2)}
                                </pre>
                              </div>
                            </div>
                          )}
                          
                          {/* 函数错误显示 */}
                          {m.functionError && (
                            <div className="mt-1 p-2 bg-red-50 border border-red-200 rounded-lg">
                              <div className="text-xs text-red-600 font-medium">
                                ❌ 操作失败: {m.functionError.error}
                              </div>
                            </div>
                          )}
                        </details>
                      </div>
                    )}
                    
                    {/* 检查是否包含图表数据 */}
                    {m.functionResult && m.functionResult.result && m.functionResult.result.data && m.functionResult.result.data.type === 'chart' ? (
                      <ChartMessage chartData={m.functionResult.result.data} />
                    ) : (
                      <ReactMarkdown
                        remarkPlugins={[remarkGfm]}
                        rehypePlugins={[rehypeHighlight]}
                        components={{
                          // 自定义样式
                          p: ({ children }) => <p className="mb-2 last:mb-0">{children}</p>,
                          ul: ({ children }) => <ul className="list-disc list-inside mb-2 space-y-1">{children}</ul>,
                          ol: ({ children }) => <ol className="list-decimal list-inside mb-2 space-y-1">{children}</ol>,
                          li: ({ children }) => <li className="text-sm">{children}</li>,
                          code: ({ children, className }) => {
                            const isInline = !className
                            return isInline ? (
                              <code className="bg-slate-100 text-slate-800 px-1 py-0.5 rounded text-xs font-mono">
                                {children}
                              </code>
                            ) : (
                              <code className={className}>{children}</code>
                            )
                          },
                          pre: ({ children }) => (
                            <pre className="bg-slate-900 text-slate-100 p-3 rounded-lg overflow-x-auto text-xs mb-2">
                              {children}
                            </pre>
                          ),
                          blockquote: ({ children }) => (
                            <blockquote className="border-l-4 border-slate-300 pl-3 italic text-slate-600 mb-2">
                              {children}
                            </blockquote>
                          ),
                          h1: ({ children }) => <h1 className="text-lg font-bold mb-2">{children}</h1>,
                          h2: ({ children }) => <h2 className="text-base font-bold mb-2">{children}</h2>,
                          h3: ({ children }) => <h3 className="text-sm font-bold mb-1">{children}</h3>,
                          strong: ({ children }) => <strong className="font-semibold">{children}</strong>,
                          em: ({ children }) => <em className="italic">{children}</em>,
                          a: ({ children, href }) => (
                            <a href={href} className="text-blue-600 hover:text-blue-800 underline" target="_blank" rel="noopener noreferrer">
                              {children}
                            </a>
                          ),
                          table: ({ children }) => (
                            <div className="overflow-x-auto mb-2">
                              <table className="min-w-full border-collapse border border-slate-300 text-xs">
                                {children}
                              </table>
                            </div>
                          ),
                          th: ({ children }) => (
                            <th className="border border-slate-300 bg-slate-100 px-2 py-1 text-left font-semibold">
                              {children}
                            </th>
                          ),
                          td: ({ children }) => (
                            <td className="border border-slate-300 px-2 py-1">
                              {children}
                            </td>
                          ),
                        }}
                      >
                        {m.content}
                      </ReactMarkdown>
                    )}
                    {i === messages.length - 1 && isStreaming && (
                      <span className="inline-block w-2 h-4 bg-indigo-500 ml-1 animate-pulse"></span>
                    )}
                  </div>
                ) : (
                  <div>
                    {m.content}
                  </div>
                )}
                
                {/* 消息操作按钮 */}
                <div className={`absolute top-2 ${m.role === 'user' ? 'left-2' : 'right-2'} opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex gap-1 z-10`}>
                  <button
                    onClick={() => handleCopyMessage(m.content)}
                    className="p-1.5 rounded-lg bg-white/90 hover:bg-white shadow-sm border border-slate-200 text-slate-600 hover:text-slate-800 transition-colors"
                    title="复制消息"
                  >
                    <Copy size={14} />
                  </button>
                  {m.role === 'user' && (
                    <button
                      onClick={() => handleEditMessage(m.messageId || '', m.content)}
                      className="p-1.5 rounded-lg bg-white/90 hover:bg-white shadow-sm border border-slate-200 text-slate-600 hover:text-slate-800 transition-colors"
                      title="编辑消息"
                    >
                      <Edit size={14} />
                    </button>
                  )}
                  <button
                    className="p-1.5 rounded-lg bg-white/90 hover:bg-white shadow-sm border border-slate-200 text-slate-600 hover:text-slate-800 transition-colors"
                    title="更多操作"
                  >
                    <MoreVertical size={14} />
                  </button>
                </div>
              </div>
            </div>
          </div>
        ))}
        {error && (
          <div className="text-center">
            <div className="inline-block px-3 py-2 bg-red-50 text-red-600 text-sm rounded-lg border border-red-200">
              {error}
            </div>
          </div>
        )}
        {messages.filter(m => m.role !== 'system').length === 0 && (
          <div className="text-center py-12">
            <div className="w-16 h-16 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-full flex items-center justify-center mx-auto mb-4">
              <span className="text-white text-2xl font-bold">AI</span>
            </div>
            <h3 className="text-lg font-semibold text-slate-900 mb-2">欢迎使用 AI 助手</h3>
            <p className="text-slate-500 text-sm max-w-md mx-auto">
              我可以帮你创建任务、调整优先级、安排时间，或者回答关于任务管理的任何问题。
            </p>
          </div>
        )}
      </div>

      {/* Task Actions */}
      {taskActions.length > 0 && (
        <div className="px-4 py-2 border-t border-slate-200 bg-slate-50">
          <div className="max-w-4xl mx-auto">
            <div className="flex flex-wrap gap-2">
              {taskActions.map((action, index) => (
                <button
                  key={index}
                  onClick={action.action}
                  className="flex items-center gap-1 px-3 py-1.5 text-xs bg-white border border-slate-200 rounded-lg hover:bg-slate-100 transition-colors"
                >
                  {action.type === 'view' && <Eye size={12} />}
                  {action.type === 'create' && <CheckCircle size={12} />}
                  {action.type === 'update' && <Edit size={12} />}
                  {action.type === 'delete' && <Trash2 size={12} />}
                  {action.label}
                </button>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Quick Replies */}
      {showQuickReplies && (
        <div className="px-4 py-3 border-t border-slate-200 bg-slate-50 max-h-60 overflow-y-auto">
          <div className="max-w-4xl mx-auto">
            <div className="text-xs text-slate-500 mb-3 font-medium">🚀 AI助手快捷功能：</div>
            
            {/* 任务管理 */}
            <div className="mb-3">
              <div className="text-xs text-slate-600 mb-2 font-medium">📋 任务管理</div>
              <div className="flex flex-wrap gap-2">
                {quickReplies.slice(0, 6).map((reply, index) => (
                  <button
                    key={index}
                    onClick={() => handleQuickReply(reply)}
                    className="px-3 py-1.5 text-xs bg-white border border-slate-200 rounded-lg hover:bg-slate-100 transition-colors shadow-sm"
                  >
                    {reply}
                  </button>
                ))}
              </div>
            </div>

            {/* 看板管理 */}
            <div className="mb-3">
              <div className="text-xs text-slate-600 mb-2 font-medium">📊 看板管理</div>
              <div className="flex flex-wrap gap-2">
                {quickReplies.slice(6, 9).map((reply, index) => (
                  <button
                    key={index + 6}
                    onClick={() => handleQuickReply(reply)}
                    className="px-3 py-1.5 text-xs bg-white border border-slate-200 rounded-lg hover:bg-slate-100 transition-colors shadow-sm"
                  >
                    {reply}
                  </button>
                ))}
              </div>
            </div>

            {/* 统计分析 */}
            <div className="mb-3">
              <div className="text-xs text-slate-600 mb-2 font-medium">📈 统计分析</div>
              <div className="flex flex-wrap gap-2">
                {quickReplies.slice(9, 13).map((reply, index) => (
                  <button
                    key={index + 9}
                    onClick={() => handleQuickReply(reply)}
                    className="px-3 py-1.5 text-xs bg-white border border-slate-200 rounded-lg hover:bg-slate-100 transition-colors shadow-sm"
                  >
                    {reply}
                  </button>
                ))}
              </div>
            </div>

            {/* 通知设置 */}
            <div className="mb-3">
              <div className="text-xs text-slate-600 mb-2 font-medium">🔔 通知设置</div>
              <div className="flex flex-wrap gap-2">
                {quickReplies.slice(13, 16).map((reply, index) => (
                  <button
                    key={index + 13}
                    onClick={() => handleQuickReply(reply)}
                    className="px-3 py-1.5 text-xs bg-white border border-slate-200 rounded-lg hover:bg-slate-100 transition-colors shadow-sm"
                  >
                    {reply}
                  </button>
                ))}
              </div>
            </div>

            {/* 图表生成 */}
            <div className="mb-2">
              <div className="text-xs text-slate-600 mb-2 font-medium">📊 图表生成</div>
              <div className="flex flex-wrap gap-2">
                {quickReplies.slice(16, 19).map((reply, index) => (
                  <button
                    key={index + 16}
                    onClick={() => handleQuickReply(reply)}
                    className="px-3 py-1.5 text-xs bg-white border border-slate-200 rounded-lg hover:bg-slate-100 transition-colors shadow-sm"
                  >
                    {reply}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Input */}
      <div className="p-4 border-t border-slate-200 bg-white flex-shrink-0">
        <div className="max-w-4xl mx-auto">
          <div className="flex items-center gap-3">
            <div className="flex-1 relative">
              <textarea
                className="w-full px-4 py-3 pr-12 rounded-2xl bg-slate-50 border border-slate-200 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all duration-200"
                placeholder={placeholder}
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault()
                    handleSend()
                  }
                }}
                disabled={recording || transcribing}
                rows={1}
                style={{ 
                  minHeight: '48px', 
                  maxHeight: '120px',
                  lineHeight: '1.5'
                }}
              />
              {/* 字符计数 */}
              {input.length > 0 && (
                <div className="absolute bottom-2 right-3 text-xs text-slate-400">
                  {input.length}
                </div>
              )}
            </div>
            
            <div className="flex items-center gap-2">
              <button
                className={`p-3 rounded-full transition-all duration-200 ${
                  showQuickReplies 
                    ? 'bg-indigo-100 text-indigo-600 hover:bg-indigo-200 shadow-md' 
                    : 'bg-slate-100 text-slate-600 hover:bg-slate-200 hover:shadow-sm'
                }`}
                onClick={() => setShowQuickReplies(!showQuickReplies)}
                title="快捷回复"
              >
                <MoreVertical size={18} />
              </button>
              
              {supported && (
                <button
                  className={`p-3 rounded-full transition-all duration-200 ${
                    recording 
                      ? 'bg-red-100 text-red-600 hover:bg-red-200 shadow-md' 
                      : 'bg-slate-100 text-slate-600 hover:bg-slate-200 hover:shadow-sm'
                  }`}
                  onClick={handleVoice}
                  title={recording ? '停止并转写' : '语音输入'}
                  disabled={transcribing}
                >
                  <Mic size={18} />
                </button>
              )}
              
              {!isStreaming ? (
                <button 
                  className={`p-3 rounded-full transition-all duration-200 ${
                    input.trim() 
                      ? 'bg-indigo-600 text-white hover:bg-indigo-700 shadow-md hover:shadow-lg' 
                      : 'bg-slate-200 text-slate-400 cursor-not-allowed'
                  }`}
                  onClick={handleSend} 
                  disabled={!input.trim() || recording || transcribing}
                  title="发送"
                >
                  <Send size={18} />
                </button>
              ) : (
                <button 
                  className="p-3 rounded-full bg-slate-200 text-slate-700 hover:bg-slate-300 transition-all duration-200 shadow-sm" 
                  onClick={cancel} 
                  title="停止"
                >
                  <div className="w-4 h-4 border-2 border-slate-700 border-t-transparent rounded-full animate-spin"></div>
                </button>
              )}
            </div>
          </div>
          
          {/* 状态提示 */}
          {(recording || transcribing) && (
            <div className="mt-3 flex items-center justify-center gap-2 text-sm">
              {recording ? (
                <>
                  <div className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></div>
                  <span className="text-red-600">正在录音，点击麦克风停止并转写…</span>
                </>
              ) : (
                <>
                  <div className="w-4 h-4 border-2 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
                  <span className="text-indigo-600">正在转写音频…</span>
                </>
              )}
            </div>
          )}
        </div>
      </div>

      {/* 编辑消息模态框 */}
      {editingMessageId && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl p-6 w-full max-w-md shadow-xl">
            <h3 className="text-lg font-semibold text-slate-900 mb-4">编辑消息</h3>
            <textarea
              className="w-full px-4 py-3 rounded-xl bg-slate-50 border border-slate-200 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all duration-200"
              placeholder="输入消息内容..."
              value={editingContent}
              onChange={(e) => setEditingContent(e.target.value)}
              rows={4}
              autoFocus
            />
            <div className="flex items-center justify-end gap-3 mt-4">
              <button
                onClick={handleCancelEdit}
                className="px-4 py-2 text-sm text-slate-600 hover:text-slate-800 transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleSaveEdit}
                disabled={!editingContent.trim()}
                className={`px-4 py-2 text-sm rounded-lg transition-colors ${
                  editingContent.trim()
                    ? 'bg-indigo-600 text-white hover:bg-indigo-700'
                    : 'bg-slate-200 text-slate-400 cursor-not-allowed'
                }`}
              >
                发送
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
